<template>
  <el-dialog title="上传文件" :visible.sync="option.isShow" width="800px" :lock-scroll=false @open="openHandle"
    @close="closeHandle">
    <el-card v-loading="loading">
      <el-alert style="margin-bottom: 5px;" title="请先选择渠道和数据来源，在上传文件" type="warning">
      </el-alert>
      <el-form label-position="right" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="渠道">
              <el-select v-model="channelTYPE" filterable clearable placeholder="请选择业渠道" size="small">
                <el-option v-for="item in channelOption" :key="item.FIELDKEY" :label="item.FIELDVALUE"
                  :value="item.FIELDKEY"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
             <el-form-item label="数据来源">
              <el-select v-model="dataFrom" filterable clearable placeholder="请选择数据来源" size="small">
                <el-option  label="003-柜面" value="003"></el-option>
              </el-select>
            </el-form-item>
          
          </el-col>
        </el-row>

      </el-form>
      <el-upload ref="upload" :action="fileUrl" :file-list="fileList" :limit="1" :on-exceed="handleExceed"
        :on-change="handleChange" :on-success="successCallback" :auto-upload="false" :on-error="handleError">
        <el-button slot="trigger" size="small" type="primary" :disabled="dataFrom==''||dataFrom== undefined||channelTYPE==''||channelTYPE== undefined">选取文件
        </el-button>
        <el-button style="margin-left: 10px;" size="small" type="success"
          :disabled="enable" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传txt文件，且不超过5MB</div>
      </el-upload>
      <!-- <el-table ref="tableData" :data='outputJSON' header-row-class-name="tableHeaderClass" border
        style="margin:10px 0 0 0">
        <el-table-column prop='DAY' label='日期'></el-table-column>
        <el-table-column prop='ISHOLIDAY' label="是否节假日" :formatter="dataFormat">
        </el-table-column>
        <el-table-column prop='ISPEAKDAY' label="是否高峰日" :formatter="dataFormat"></el-table-column>
      </el-table> -->
    </el-card>
    <span slot="footer" class="dialog-footer">
      <el-button @click="option.isShow=false" size="mini">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
  import request from "@/common/utils/requestWFM";
  import getGlobalParams from "@/common/utils/getGlobalParams";
  import dataAdd from '@/message/wfm/FTEForecast/originalBusinessData/dataImport'
  import pathCheck from "@/message/QCManage/caseManage/pathCheck";
  import requestQC from "@/common/utils/requestQC";
  import dictionary from '@/message/wfm/baseData/dictionaryManage/dictionaryQuery'

  export default {
    props: ['option'],
    data() {
      return {
        channelOption: [],
        dataFrom: '',//数据来源
        channelTYPE: '',
        holidayOption: [{
            label: '节假日',
            value: 'Y'
          },
          {
            label: '非节假日',
            value: 'N',
          }
        ],
        ISPEAKDAYOption: [{
            label: '高峰日',
            value: 'Y'
          },
          {
            label: '非高峰日',
            value: 'N',
          }
        ],
        fileUrl: "",
        fileList: [],
        filepath: "",
        // fileDownUrl: "",
        enable: true,
        loading: false,
        outputJSON: [],
        queryBtn: false
      };
    },
    created() {
      this.dictionaryQuery('CHANNELTYPE').then(value => this.channelOption = value);

      // 获取版本上传地址
      // this.fileUrl = getGlobalParams.get("KnowledgeFileUploadAddress");
      // this.fileDownUrl = getGlobalParams.get("KnowledgeFileDownloadAddress");
    },
    methods: {
      async dictionaryQuery(type) {
        let resBody = new dictionary();
        resBody.data.FIELDCODE = type
        resBody.data.CurrPage = 1
        resBody.data.PageRowNum = 400
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          return response.BODY.FIEDATA;
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      findName(arr, val) {
        let data = arr.filter(item => {
          return item.value == val
        })
        if (data.length)
          return data[0].value + ' - ' + data[0].label
      },
      dataFormat(row, column) {
        //枚举设备形式
        if (column.property == "ISHOLIDAY")
          return this.findName(this.holidayOption, row[column.property]);
        if (column.property == "ISPEAKDAY")
          return this.findName(this.ISPEAKDAYOption, row[column.property]);
        // if (column.property == "ISVALID")
        //   return this.findName(this.valueOption,row[column.property]);
      },
      openHandle() {
        // this.initPop();
      },
      submitUpload() {
        this.$refs.upload.submit();
      },
      // 大于一个文件提示信息
      handleExceed(files, fileList) {
        this.$message.warning(`只能上传一个文件！`);
      },
      // 上传成功的回调
      async successCallback(val, file) {
        console.log("this.filepath", this.filepath);
        this.loading = true;
        let resBody = new dataAdd();
        resBody.data.FILESOURCE = this.channelTYPE
        resBody.data.FILENAME = file.name;
        resBody.data.FILEPATH = 'share/' + this.filepath + '/';
        let response = await request(resBody);
        this.loading = false;
        if (response.SYS_HEAD.ReturnCode == "000000") {
          // console.log("===========", response.RSP_BODY);
          // if (response.BODY.FAILNUM > 0) {
          //   this.$message({
          //     message: '部分导入成功的，但' + response.BODY.WARNDESC,
          //     type: 'warning'
          //   });
          // } else {
            this.$message({
              type: "success",
              message: "文件上传成功"
            });
          // }
          this.$emit("ListenSuccess");
          this.option.isShow = false
        } else {
          this.fileList = [];
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          });
        }
      },
      handleError() {
        this.$message.warning(`文件上传失败！`);
      },
      closeHandle() {
        this.initPop();
      },

      initPop() {
        this.outputJSON = [];
        this.queryBtn = false;
        this.enable = true 
        this.dataFrom = ''
        this.channelTYPE = ''
        this.fileList = [];
      },
      async checkPath() {
        let date = new Date()
        let y = date.getFullYear()
        let m = date.getMonth() + 1
        m = m < 10 ? '0' + m : m
        let d = date.getDate()
        d = d < 10 ? ('0' + d) : d
        let currentDate = y + m + d
        let user = this.$store.getters.UserNum
        this.fileUrl = getGlobalParams.get("uploadAddress")
        let resBody = new pathCheck();
        resBody.data.FILEPATH = 'WFM/' + currentDate + '/' + this.channelTYPE + '/' + user+'/'+this.dataFrom
        let response = await requestQC(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          var reg = new RegExp('/', "g")
          this.filepath = response.BODY.PATH
          this.fileUrl += '/' + response.BODY.PATH.replace(reg, '_')
          console.log(this.fileUrl)

        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },

      handleChange(file, fileList) {
        var vueIns = this;
        var IMPORTFILE_MAXSIZE = 1 * 5120;
        const isLt5M = file.size / 1024 < IMPORTFILE_MAXSIZE;
        //控制导入文件大小
        //判断是否有文件
        if (!file) {
          vueIns.$message({
            message: "请选择文件",
            type: 'error  '
          });
          vueIns.outputJSON = [];
          return
        }
        if (!isLt5M) {
          this.$message.error('上传文件大小不能超过 5MB!');
          vueIns.outputJSON = [];
          file = "";
          return
        }
        //判断格式
        // console.log(fileData);
        var tempArr = file.name.split(".");
        var suffix = tempArr[tempArr.length - 1];
        if (suffix != 'txt') {
          vueIns.$message({
            message: "文件格式不正确",
            type: 'error  '
          });
          vueIns.outputJSON = [];
          file = "";
          this.fileList = []
          return
        }
        vueIns.enable = false
        // var reader = new FileReader();
        // reader.onloadend = async function (e) {
        //   var data = e.target.result;
        //   var workbook = vueIns.XLSX.read(data, {
        //     type: 'binary'
        //   });
        //   var sheetObject = workbook.Sheets[workbook.SheetNames[0]];
        //   delete sheetObject.A1;
        //   var temp = JSON.parse(JSON.stringify(vueIns.XLSX.utils.sheet_to_json(sheetObject)));
        //   var outPutArr = [];
        //   temp.splice(0, 1);
        //   console.log("outPutArr", temp);
        //   for (var i = 0; i < temp.length; i++) {
        //     var quesContent = new Object();
        //     quesContent.DAY = temp[i].__EMPTY;
        //     quesContent.ISHOLIDAY = temp[i].__EMPTY_1;
        //     quesContent.ISPEAKDAY = temp[i].__EMPTY_2;
        //     outPutArr.push(
        //       quesContent
        //     );
        //   }
        //   console.log(outPutArr)
        //   if (outPutArr[0].DAY && outPutArr[0].ISHOLIDAY && outPutArr[0].ISPEAKDAY) {
        //     vueIns.outputJSON = outPutArr;
        //     console.log(vueIns.outputJSON);
        //     vueIns.queryBtn = true;
        //     vueIns.enable = false;
        //   } else {
        //     vueIns.$message({
        //       message: "请遵循对应格式",
        //       type: 'error  '
        //     });
        //     vueIns.outputJSON = [];
        //     return
        //   }
        // };
        // reader.readAsBinaryString(file.raw);
        this.checkPath()
      }
    }
  };

</script>

<style scoped>

</style>
